package ppjava12v1.chess.entities.users;

import ppjava12v1.chess.enums.Role;

import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;


/**
 * Класс пользователя. Используется для входа на сайт, к нему привязаны
 * классы права пользователя и профиль пользователя
 */
@Entity
@Table(name = "users", uniqueConstraints = { @UniqueConstraint(name = "uc_login", columnNames = "login") })
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "login", unique = true, nullable = false)
    private String login;

    @Column
    private String password;

    @Column
    private boolean active;

    @Transient
    private Set<Role> roles;

    @OneToOne(targetEntity = UserProfile.class,fetch = FetchType.EAGER,
            cascade = CascadeType.ALL, mappedBy = "user")
    private UserProfile profile;

    public User() {
        roles = new HashSet<>();
        profile = new UserProfile();
        profile.setUser(this);
    }

    public UserProfile getProfile() {
        return profile;
    }

    public void setProfile(UserProfile profile) {
        this.profile = profile;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof User)) return false;

        User user = (User) o;

        if (id != user.id) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return (int) (id ^ (id >>> 32));
    }

    public boolean add(Role role) {
        return roles.add(role);
    }

    public boolean remove(Role role) {
        return roles.remove(role);
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", login='" + login + '\'' +
                ", password='" + "****" + '\'' +
                ", active=" + active +
                ", roles=" + roles +
                ", " + profile +
                '}';
    }
}
